package org.tlang.interpreter;

import org.tlang.ast.AST;
import org.tlang.context.Context;
import org.tlang.exception.ParseException;
import org.tlang.exception.TypeException;
import org.tlang.lexer.Lexer;
import org.tlang.parser.Parser;

import java.util.List;

public abstract class AbsInterpreter implements Interpreter {

    @Override
    public Object eval(String text) throws ParseException, TypeException {
        Lexer lexer = new Lexer();
        lexer.parse(text);

        Parser parser = createParser(lexer);
        AST ast = parser.parse(lexer);

        return execute(ast);
    }

    protected Context createGlobalContext() {
        return new Context();
    }

    @Override
    public Object eval(List<String> texts) throws ParseException, TypeException {
        Lexer lexer = new Lexer();
        lexer.parse(texts);

        Parser parser = createParser(lexer);
        AST ast = parser.parse(lexer);

        return execute(ast);
    }

    private Object execute(AST ast) throws TypeException {
        Context context = createGlobalContext();

        // 查找符号表 和 类型定义
        ast.lookup(context.symbolTable(), context.typeTable());

        // 静态类型检查
//        ast.typeCheck(globalContext.typeTable());

        // 解释执行
        Object result = ast.eval(context.valueTable());
        return result;
    }

    protected abstract Parser createParser(Lexer lexer);
}
